package top.honlnk.czuan.common.config;

import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.honlnk.czuan.common.interceptor.JWTInterceptor;
import top.honlnk.czuan.common.interceptor.PowerInterceptor;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(@NotNull PathMatchConfigurer configurer) {
        // 指定controller统一的接口前缀
        configurer.addPathPrefix("/api", c -> c.isAnnotationPresent(RestController.class));
    }
    @Override
    public void addCorsMappings(@NotNull CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }

    /**
     * 加入自定义拦截器JWTInterceptor，设置拦截规则
     */
    @Resource
    private JWTInterceptor jwtInterceptor;
    @Resource
    private PowerInterceptor powerInterceptor;
    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        // 登录检查，JWT合法性校验
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/user/login");

        // 权限检查，检查初登录，以及获取用户信息以外的所有接口的权限是否符合要求的权限
        registry.addInterceptor(powerInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/user/login")
                .excludePathPatterns("/api/user/getUser");
    }
}
